﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace BaiTu.Framework.MVCFramework.WorkContext
{
    /// <summary>
    /// Web工作上下文环境
    /// </summary>
    public class WebWorkContext : IWorkContext
    {
        #region Const

        private const string CustomerCookieName = "baitu.customer";

        #endregion

        #region Fields
        private readonly HttpContextBase _httpContext;

        #endregion

        #region Ctor
        public WebWorkContext(HttpContextBase httpContext)
        {
            this._httpContext = httpContext;
        }

        #endregion

        #region Utilities
        protected virtual HttpCookie GetCustomerCookie()
        {
            if (_httpContext == null || _httpContext.Request == null)
                return null;

            return _httpContext.Request.Cookies[CustomerCookieName];
        }
        protected virtual void SetCustomerCookie(Guid customerGuid)
        {
            if (_httpContext != null && _httpContext.Response != null)
            {
                var cookie = new HttpCookie(CustomerCookieName);
                cookie.HttpOnly = true;
                cookie.Value = customerGuid.ToString();
                if (customerGuid == Guid.Empty)
                {
                    cookie.Expires = DateTime.Now.AddMonths(-1);
                }
                else
                {
                    int cookieExpires = 24 * 365; //TODO make configurable
                    cookie.Expires = DateTime.Now.AddHours(cookieExpires);
                }

                _httpContext.Response.Cookies.Remove(CustomerCookieName);
                _httpContext.Response.Cookies.Add(cookie);
            }
        }
        /// <summary>
        /// 用户类型
        /// </summary>
        public virtual Users.UserType UserType { get; set; }
        #endregion
    }
}
